import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormHelperText,
  Grid,
  IconButton,
  Divider,
  CircularProgress,
} from '@mui/material';
import { ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import axios from 'axios';

const CategoryForm = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const isEditMode = !!id;

  const [formData, setFormData] = useState({
    name: '',
    description: '',
    parent_id: null,
  });

  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [errors, setErrors] = useState({});

  useEffect(() => {
    // 获取分类列表
    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category?all=true');
        setCategories(response.data);
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    };

    fetchCategories();
    
    // 如果不是编辑模式，从URL参数中获取父分类ID
    if (!isEditMode) {
      const searchParams = new URLSearchParams(location.search);
      const parentId = searchParams.get('parent_id');
      if (parentId) {
        setFormData(prev => ({
          ...prev,
          parent_id: parseInt(parentId)
        }));
      }
    }

    // 如果是编辑模式，获取分类详情
    if (isEditMode) {
      const fetchCategory = async () => {
        setLoading(true);
        try {
          const response = await axios.get(`/api/category/${id}`);
          const category = response.data;
          
          setFormData({
            name: category.name || '',
            description: category.description || '',
            parent_id: category.parent_id,
          });
        } catch (error) {
          console.error('获取分类详情失败:', error);
        } finally {
          setLoading(false);
        }
      };

      fetchCategory();
    }
  }, [id, isEditMode]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value === '' ? null : value
    }));
    
    // 清除错误
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  const validate = () => {
    const newErrors = {};
    
    if (!formData.name.trim()) {
      newErrors.name = '分类名称不能为空';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!validate()) return;
    
    setSubmitting(true);
    
    try {
      if (isEditMode) {
        // 更新分类
        await axios.put(`/api/category/${id}`, formData);
      } else {
        // 创建分类
        await axios.post('/api/category', formData);
      }
      
      navigate('/categories');
    } catch (error) {
      console.error('保存分类失败:', error);
      alert('保存失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  // 过滤掉当前分类及其子分类（编辑模式下）
  const getAvailableParentCategories = () => {
    if (!isEditMode) return categories;
    
    // 递归查找所有子分类ID
    const findAllChildrenIds = (categoryId) => {
      const childrenIds = [];
      const findChildren = (id) => {
        const children = categories.filter(c => c.parent_id === id);
        children.forEach(child => {
          childrenIds.push(child.id);
          findChildren(child.id);
        });
      };
      findChildren(categoryId);
      return childrenIds;
    };
    
    const childrenIds = findAllChildrenIds(parseInt(id));
    return categories.filter(c => c.id !== parseInt(id) && !childrenIds.includes(c.id));
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ mb: 2, display: 'flex', alignItems: 'center' }}>
        <IconButton onClick={handleBack} sx={{ mr: 1 }}>
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h5">
          {isEditMode ? '编辑分类' : '新建分类'}
        </Typography>
      </Box>

      <Paper elevation={1} sx={{ p: 3 }}>
        <Box component="form" onSubmit={handleSubmit}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="分类名称"
                name="name"
                value={formData.name}
                onChange={handleChange}
                error={!!errors.name}
                helperText={errors.name}
                required
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="描述"
                name="description"
                value={formData.description || ''}
                onChange={handleChange}
                multiline
                rows={3}
                placeholder="可选，分类的描述信息..."
              />
            </Grid>
            
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>父分类</InputLabel>
                <Select
                  name="parent_id"
                  value={formData.parent_id || ''}
                  onChange={handleChange}
                  label="父分类"
                >
                  <MenuItem value="">无（顶级分类）</MenuItem>
                  {getAvailableParentCategories().map((category) => (
                    <MenuItem key={category.id} value={category.id}>
                      {category.name}
                    </MenuItem>
                  ))}
                </Select>
                <FormHelperText>可选，选择此分类的父分类</FormHelperText>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <Divider sx={{ my: 2 }} />
              <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
                <Button
                  variant="outlined"
                  onClick={handleBack}
                >
                  取消
                </Button>
                <Button
                  type="submit"
                  variant="contained"
                  disabled={submitting}
                >
                  {submitting ? <CircularProgress size={24} /> : '保存'}
                </Button>
              </Box>
            </Grid>
          </Grid>
        </Box>
      </Paper>
    </Box>
  );
};

export default CategoryForm;